import React, { useState, useEffect, useCallback } from 'react';
import styled from 'styled-components';
import { motion, AnimatePresence } from 'framer-motion';
import { useNavigate } from 'react-router-dom';

// Assuming back-icon is also needed for consistency, or a different navigation method
import backIcon from '../assets/images/back-icon.png'; 

// Import mood icons
import happyIcon from '../assets/images/happy-icon.png'; 
import sadIcon from '../assets/images/sad-icon.png';   
import angryIcon from '../assets/images/angry-icon.png';  
import calmIcon from '../assets/images/peaceful.png';   // Changed from calmIcon.png if that was the old name
import confusedIcon from '../assets/images/confused-icon.png'; 
import anxiousIcon from '../assets/images/anxiety-icon.png'; 
import enlightenedIcon from '../assets/images/bright-icon.png'; 

// Updated moodData order and ensured IDs are unique and simple
const moodData = [
  { name: '开心', icon: happyIcon, id: 'mood-happy' },
  { name: '难过', icon: sadIcon, id: 'mood-sad' },
  { name: '愤怒', icon: angryIcon, id: 'mood-angry' },
  { name: '困惑', icon: confusedIcon, id: 'mood-confused' },
  { name: '平静', icon: calmIcon, id: 'mood-calm' },
  { name: '焦虑', icon: anxiousIcon, id: 'mood-anxious' },
  { name: '开悟', icon: enlightenedIcon, id: 'mood-enlightened' },
];

interface DiaryHistoryEntry {
  id: number;
  userId: number;
  date: string; // YYYY-MM-DD
  mood: number; // Assuming backend returns mood as a number (1-7)
  diary: string;
  createTime: string; // ISO timestamp
  updateTime: string; // ISO timestamp
}

const pageVariants = {
  initial: { opacity: 0 },
  in: { opacity: 1 },
  out: { opacity: 0 },
};

const PageContainer = styled(motion.div)`
  min-height: 100vh;
  width: 100vw;
  background: linear-gradient(160deg, #e0eafc 0%, #cfdef3 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  padding-top: 90px; /* Increased for header + potential back button */
  box-sizing: border-box;
  position: relative;
`;

const Header = styled(motion.header)`
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  padding: 18px 0; /* Slightly more padding */
  background-color: rgba(255, 255, 255, 0.65);
  backdrop-filter: blur(12px);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.07);
  z-index: 10;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center; /* Keep title centered */
  /* Removed justify-content: center; to allow button on left */
`;

const BackButton = styled.button` /* If back button is needed */
  background: url(${backIcon}) no-repeat center center;
  background-size: contain;
  width: 24px;
  height: 24px;
  border: none;
  cursor: pointer;
  position: absolute;
  left: 20px;
  top: 50%;
  transform: translateY(-50%);
  opacity: 0.7;
  transition: opacity 0.2s ease;
  &:hover { opacity: 1; }
`;

const Title = styled(motion.h1)`
  font-size: 1.5rem; /* Slightly reduced for balance */
  color: #2c3e50; /* Darker, more grounded blue */
  font-weight: 500;
  margin: 0;
`;

const MoodLoggingSection = styled(motion.section)`
  background: rgba(255, 255, 255, 0.45);
  backdrop-filter: blur(15px);
  border-radius: 22px; /* Softer radius */
  padding: 30px;
  width: 100%;
  max-width: 580px; /* Adjusted width */
  box-shadow: 0 10px 35px rgba(0, 0, 0, 0.12);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 28px; /* Adjusted gap */
  margin-bottom: 35px;
`;

const sectionVariants = {
  hidden: { opacity: 0, y: 20 },
  visible: {
    opacity: 1,
    y: 0,
    transition: {
      duration: 0.5,
      ease: "easeOut",
      staggerChildren: 0.1
    }
  }
};

const itemVariants = {
  hidden: { opacity: 0, y: 15 },
  visible: { opacity: 1, y: 0, transition: { duration: 0.4, ease: "easeOut" } }
};

const MoodIconsContainer = styled(motion.div)`
  display: flex;
  justify-content: center; /* Center icons if they don't fill the row */
  flex-wrap: wrap;
  gap: 18px; /* Increased gap for better spacing */
  width: 100%;
`;

const MoodIconButton = styled(motion.button)<{ selected: boolean }>`
  background-color: ${({ selected }) => selected ? 'rgba(255, 255, 255, 0.9)' : 'rgba(255, 255, 255, 0.5)'};
  border: 2px solid;
  border-color: ${({ selected }) => selected ? '#007aff' : 'rgba(0, 0, 0, 0.08)'};
  border-radius: 18px; /* Softer radius */
  padding: 12px;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: ${({ selected }) => selected ? '0 4px 15px rgba(0, 122, 255, 0.25)' : '0 2px 6px rgba(0,0,0,0.07)'};
  transition: transform 0.2s cubic-bezier(0.22, 1, 0.36, 1), 
              border-color 0.2s ease-out, 
              box-shadow 0.2s ease-out,
              background-color 0.2s ease-out;
  outline: none;
  
  img {
    width: 48px; 
    height: 48px;
    display: block;
    margin-bottom: 6px;
  }

  span {
    font-size: 0.75rem;
    color: ${({ selected }) => selected ? '#007aff' : '#4a5568'};
    font-weight: ${({ selected }) => selected ? '500' : 'normal'};
  }

  &:hover {
    transform: translateY(-3px);
    border-color: ${({ selected }) => selected ? '#007aff' : 'rgba(0, 122, 255, 0.5)'};
    box-shadow: ${({ selected }) => selected ? '0 6px 20px rgba(0, 122, 255, 0.3)' : '0 4px 12px rgba(0,0,0,0.1)'};
  }
`;

const StyledTextArea = styled(motion.textarea)`
  width: 100%;
  min-height: 120px;
  padding: 18px;
  border-radius: 18px;
  border: 1px solid rgba(0, 0, 0, 0.12);
  background-color: rgba(255, 255, 255, 0.75);
  font-size: 0.95rem;
  color: #333;
  resize: vertical;
  box-shadow: inset 0 1px 4px rgba(0,0,0,0.06);
  transition: border-color 0.2s ease, background-color 0.2s ease;

  &:focus {
    outline: none;
    border-color: #007aff;
    background-color: rgba(255, 255, 255, 0.95);
    box-shadow: inset 0 1px 4px rgba(0,0,0,0.06), 0 0 0 2px rgba(0,122,255,0.1);
  }
`;

const SubmitButton = styled(motion.button)`
  padding: 14px 35px;
  border: none;
  border-radius: 28px;
  background: linear-gradient(135deg, #007bff 0%, #0056b3 100%); /* Adjusted gradient */
  color: white;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  box-shadow: 0 4px 15px rgba(0, 97, 255, 0.2);
  transition: transform 0.15s ease, box-shadow 0.2s ease;

  &:hover:not(:disabled) {
    transform: scale(1.03) translateY(-1px);
    box-shadow: 0 6px 20px rgba(0, 97, 255, 0.3);
  }
  &:active:not(:disabled) {
    transform: scale(0.98);
  }
`;

// Placeholder for History Section
const HistorySection = styled(motion.section)`
  width: 100%;
  max-width: 580px;
  /* Styles for history cards later */
  display: flex; /* Added to allow gap and column layout */
  flex-direction: column; /* Stack cards vertically */
  gap: 20px; /* Space between cards */
`;

const DiaryCard = styled(motion.div)`
  background: rgba(255, 255, 255, 0.55); /* Slightly more opaque for readability */
  backdrop-filter: blur(10px);
  border-radius: 18px;
  padding: 20px;
  box-shadow: 0 6px 25px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  gap: 12px;
`;

const CardHeader = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
`;

const CardDate = styled.span`
  font-size: 0.9rem;
  color: #555;
  font-weight: 500;
`;

const CardMoodIcon = styled.img`
  width: 32px; /* Smaller icon for card header */
  height: 32px;
`;

const CardText = styled.p`
  font-size: 0.9rem;
  color: #333;
  line-height: 1.6;
  white-space: pre-wrap; /* Preserve line breaks from diary entry */
  margin: 0;
`;

const RecordPage: React.FC = () => {
  const [selectedMoodId, setSelectedMoodId] = useState<string | null>(null);
  const [diaryText, setDiaryText] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [submitStatus, setSubmitStatus] = useState<'idle' | 'success' | 'error' | 'loading'>('idle');
  const [feedbackMessage, setFeedbackMessage] = useState<string>('');
  const navigate = useNavigate();

  const [historyEntries, setHistoryEntries] = useState<DiaryHistoryEntry[]>([]);
  const [isHistoryLoading, setIsHistoryLoading] = useState(true);
  const [historyError, setHistoryError] = useState<string | null>(null);

  const fetchHistory = useCallback(async () => {
    const userId = localStorage.getItem('userId');
    if (!userId) {
      setHistoryError('用户未登录，无法获取历史记录。');
      setIsHistoryLoading(false);
      return;
    }

    setIsHistoryLoading(true);
    setHistoryError(null);

    try {
      const response = await fetch(`http://localhost:8111/api/getDiary/${userId}`);
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({ message: `服务器错误，状态码: ${response.status}` }));
        throw new Error(errorData.message || '获取日记历史失败');
      }
      const result = await response.json();
      const data: DiaryHistoryEntry[] = result.data || [];
      data.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime() || new Date(b.createTime).getTime() - new Date(a.createTime).getTime());
      setHistoryEntries(data);
    } catch (error) {
      console.error('Failed to fetch diary history:', error);
      if (error instanceof Error) {
        setHistoryError(error.message);
      } else {
        setHistoryError('获取历史记录时发生未知错误。');
      }
    } finally {
      setIsHistoryLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchHistory();
  }, [fetchHistory]);

  const handleBack = () => navigate(-1);

  const handleMoodSelect = (moodId: string) => {
    setSelectedMoodId(moodId);
    setSubmitStatus('idle');
    setFeedbackMessage('');
  };

  const handleSubmitDiary = async () => {
    if (!selectedMoodId) {
      setFeedbackMessage('请选择一个心情哦～');
      setSubmitStatus('error');
      return;
    }
    if (!diaryText.trim()) {
      setFeedbackMessage('日记内容不能为空哦～');
      setSubmitStatus('error');
      return;
    }

    const userId = localStorage.getItem('userId');
    if (!userId) {
      setFeedbackMessage('用户未登录，无法记录日记。');
      setSubmitStatus('error');
      // Potentially navigate to login: navigate('/login');
      return;
    }

    setIsLoading(true);
    setSubmitStatus('loading');
    setFeedbackMessage('');

    const currentDate = new Date().toISOString().split('T')[0]; // YYYY-MM-DD
    const moodIndex = moodData.findIndex(mood => mood.id === selectedMoodId);
    const moodNumber = moodIndex !== -1 ? moodIndex + 1 : 0; // Backend expects 1-based mood number

    if (moodNumber === 0) {
        setFeedbackMessage('选择的心情无效，请重试。');
        setSubmitStatus('error');
        setIsLoading(false);
        return;
    }

    const currentTimestamp = new Date().toISOString(); // Get current ISO timestamp

    const diaryEntry = {
      // id: null, // Typically set by backend
      userId: parseInt(userId, 10),
      date: currentDate,
      mood: moodNumber,
      diary: diaryText.trim(),
      createTime: currentTimestamp, // Add current timestamp
      updateTime: currentTimestamp, // Add current timestamp
    };

    try {
      const response = await fetch('http://localhost:8111/api/addDiary', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(diaryEntry),
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({ message: `服务器错误，状态码: ${response.status}` }));
        throw new Error(errorData.message || `日记提交失败`);
      }

      const resultWrapper = await response.json(); // Expect a wrapper object

      if (resultWrapper && resultWrapper.data) { // Check for 'data' property
        const newActualDiary: DiaryHistoryEntry = resultWrapper.data; // Extract the actual diary object

        setSubmitStatus('success');
        setFeedbackMessage('日记已成功记录！✨');
        setSelectedMoodId(null); // Reset mood selection
        setDiaryText('');      // Clear textarea
        
        setHistoryEntries(prevEntries => 
          [newActualDiary, ...prevEntries].sort((a, b) => 
            new Date(b.date).getTime() - new Date(a.date).getTime() || 
            new Date(b.createTime).getTime() - new Date(a.createTime).getTime()
          )
        );
        setIsLoading(false); // Ensure loading is false after successful state update
      } else {
        console.error('Diary submission was successful (HTTP 2xx) but response.data is missing or invalid:', resultWrapper);
        setSubmitStatus('error');
        setFeedbackMessage(resultWrapper.message || '日记已记录，但无法立即在列表中显示。正在尝试刷新...');
        fetchHistory(); 
      }

    } catch (error) {
      console.error('Failed to submit diary:', error);
      setSubmitStatus('error');
      if (error instanceof Error) {
        setFeedbackMessage(error.message || '提交日记时发生未知错误。');
      } else {
        setFeedbackMessage('提交日记时发生未知错误。');
      }
    } finally {
      setIsLoading(false); 
    }
  };

  return (
    <PageContainer
      initial="initial"
      animate="in"
      exit="out"
      variants={pageVariants}
      transition={{ duration: 0.3 }}
    >
      <Header initial={{ opacity: 0, y: -20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.5, delay: 0.1, ease: "easeOut" }}>
        <BackButton onClick={handleBack} />
        <Title>情绪日记</Title>
      </Header>

      <MoodLoggingSection variants={sectionVariants} initial="hidden" animate="visible">
        <motion.p variants={itemVariants} style={{ fontSize: '1.1rem', color: '#2c3e50', margin: 0, fontWeight: 400 }}>
          今天你的心情怎么样？
        </motion.p>
        <MoodIconsContainer variants={itemVariants}> 
          {moodData.map((mood) => (
            <MoodIconButton
              key={mood.id}
              selected={selectedMoodId === mood.id}
              onClick={() => handleMoodSelect(mood.id)}
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              animate={{
                scale: selectedMoodId === mood.id ? 1.12 : 1,
                borderColor: selectedMoodId === mood.id ? '#007aff' : 'rgba(0, 0, 0, 0.08)',
                transition: { type: 'spring', stiffness: 350, damping: 12 }
              }}
            >
              <motion.img src={mood.icon} alt={mood.name} />
              <span>{mood.name}</span>
            </MoodIconButton>
          ))}
        </MoodIconsContainer>
        <StyledTextArea
          variants={itemVariants}
          placeholder="记录下此刻的想法和感受吧..."
          value={diaryText}
          onChange={(e) => setDiaryText(e.target.value)}
        />
        <SubmitButton
          variants={itemVariants}
          onClick={handleSubmitDiary}
          disabled={isLoading}
          whileHover={{ scale: !isLoading ? 1.03 : 1, y: !isLoading ? -1 : 0 }}
          whileTap={{ scale: !isLoading ? 0.98 : 1 }}
        >
          {isLoading ? '记录中...' : '记录今日心情'}
        </SubmitButton>
        {feedbackMessage && (
          <motion.p
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            style={{
              marginTop: '15px',
              fontSize: '0.9rem',
              color: submitStatus === 'error' ? '#e53e3e' : '#2c3e50',
            }}
          >
            {feedbackMessage}
          </motion.p>
        )}
      </MoodLoggingSection>

      <HistorySection variants={sectionVariants} initial="hidden" animate="visible" >
        {isHistoryLoading && <p>正在加载历史记录...</p>}
        {historyError && <p style={{ color: '#e53e3e' }}>{historyError}</p>}
        {!isHistoryLoading && !historyError && historyEntries.length === 0 && (
          <p>暂无日记记录。</p>
        )}
        {!isHistoryLoading && !historyError && historyEntries.map(entry => {
          const mood = moodData.find(m => m.id === `mood-${m.name.toLowerCase()}` || moodData.indexOf(m) + 1 === entry.mood ); // Simplified mood finding logic
          return (
            <DiaryCard 
              key={entry.id} 
              variants={itemVariants} 
              initial="hidden" 
              animate="visible"
              layout // Added for smoother animation on list changes
            >
              <CardHeader>
                <CardDate>{new Date(entry.date).toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' })}</CardDate>
                {mood && <CardMoodIcon src={mood.icon} alt={mood.name} />}
              </CardHeader>
              <CardText>{entry.diary}</CardText>
            </DiaryCard>
          );
        })}
      </HistorySection>
    </PageContainer>
  );
};

export default RecordPage;
